import webview
import win32gui
import win32con
import win32api
import time
from pynput import keyboard
import threading
import os
import json
import requests
import datetime
window = None
child_window = None
listener = None
num_windows = 0
requied_kg = True
ontimer = None
baseconfig = {
    "title": "5",
    "debug": False,
    "url": "https://tgolf.ysy12.cn",
    "fullscreen":True,
    "log":True
}

def get_config():
    fileName = 'config.json'
    if os.path.exists(fileName):
        with open(fileName, 'r') as f:
            config = json.load(f)
    else:
        with open(fileName, 'w') as f:
            json.dump(baseconfig, f,  indent=4)
        config = baseconfig
    return config
def start_global_listener():
    def on_press(key):
        try:
            # 检测F11键（跨平台兼容）
            if key == keyboard.Key.f11:
                global num_windows
                num_windows += 1
                global window
                if num_windows>=9:
                    window.evaluate_js("test(true)")
                    num_windows = 0
                else:
                    window.evaluate_js("test(false)")
                pass
        except AttributeError:
            pass  # 忽略非F11键
    global listener
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
def create_child_window():
    global child_window
    child_window = webview.create_window('子窗口', url='static/child_index.html',
                                         width=600,
                                         height=100,
                                         hidden=True,
                                         )
    # child_window.hide()
    # screen_width = win32api.GetSystemMetrics(0)
    # width = int((screen_width-600)/2)
    # child_window.move(width,0)
    # child_window.hide()
    # child_window.move()
def hide_child_window():
    global child_window
    if child_window:
        child_window.hide()
def close_child_window():
    global child_window
    if child_window:
        child_window.destroy()
        child_window = None
    global listener
    if listener:
        listener.stop()
    global requied_kg
    requied_kg = False
    global ontimer
    if ontimer:
        ontimer.cancel()

def find_window_by_title(title):
    hwnd = win32gui.FindWindow(None, title)
    return hwnd
def require_hand():
    if requied_kg:
        print("请求上游")
        newconfig = get_config()
        url = newconfig["url"]+"/api/muyuxuan/daily"
        res = requests.post(url, data={"title": newconfig["title"]})
        res = res.json()
        if newconfig["log"]:
            ndate = datetime.datetime.now()
            newFileName = f"logs/{ndate.year}-{ndate.month}-{ndate.day}.log"
            res_str = json.dumps(res,ensure_ascii=False)
            message = f"{ndate.year}-{ndate.month}-{ndate.day} {ndate.hour}:{ndate.minute}:{ndate.second}:数据：{res_str}\n"
            if not os.path.exists(newFileName):
                os.makedirs(os.path.dirname(newFileName), exist_ok=True)
            with open(newFileName, "a",encoding="utf8") as f:
                f.write(message)
            # print(res)
        if res["code"]==1:
            global window
            window.evaluate_js(f"get_response({res["data"]})")
            if res["data"]["status"]==1:
                window.show()
            elif res["data"]["status"]==5:
                window.hide()
            elif res["data"]["status"]==2:
                window.hide()
            elif res["data"]["status"]==6:
                window.hide()
                global child_window
                if child_window:
                    child_window.show()
                    screen_width = win32api.GetSystemMetrics(0)
                    width = int((screen_width-600)/2)
                    child_window.move(width,0)
                    threading.timer(interval= 5,function = hide_child_window).start()

        global ontimer
        ontimer = threading.Timer(interval=5,  function=require_hand)
        ontimer.start()

def set_window_transparent(title, transparency=0):
    # 等待窗口出现
    hwnd = 0
    while hwnd == 0:
        hwnd = find_window_by_title(title)
        time.sleep(0.5)

    # 设置分层窗口属性
    win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
                           win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)
    win32gui.SetLayeredWindowAttributes(hwnd, 0, transparency, win32con.LWA_ALPHA)
    require_hand()
    create_child_window()


class MyClass():
    def nameclose(self):
        global window
        if window:
            window.destroy()

if __name__ == '__main__':
    title = 'Pywebview'
    newconfigig = get_config()
    window = webview.create_window(title, url='static/index.html',js_api=MyClass(),fullscreen=newconfigig["fullscreen"])
    start_global_listener()
    window.events.loaded += lambda: set_window_transparent(title, transparency=200,)
    window.events.closed += close_child_window
    webview.start(http_server=True,gui='edgechromium',debug=newconfigig["debug"])